<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <title>菜单管理</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>菜单管理</h2>

<div class="action-buttons">
    <button class="btn btn-primary" onclick="showAddModal()"><i class="fas fa-plus"></i> 新增菜单</button>
    <button class="btn btn-info" id="editBtn" onclick="editSelectedMenu()" disabled><i class="fas fa-edit"></i> 编辑</button>
    <button class="btn btn-danger" id="deleteBtn" onclick="deleteSelectedMenu()" disabled><i class="fas fa-trash"></i> 删除</button>
    <button class="btn btn-success" id="assignBtn" onclick="openAssignModal()" disabled><i class="fas fa-share-square"></i> 分配菜单</button>
</div>

<table>
    <thead>
    <tr>
        <th></th>
        <th>ID</th>
        <th>菜单名称</th>
        <th>链接</th>
        <th>父级ID</th>
        <th>排序</th>
        <th>备注</th>
    </tr>
    </thead>
    <tbody id="menuTableBody"></tbody>
</table>

<!-- 菜单模态框 -->
<div class="modal" id="menuModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">菜单信息</h3>
        </div>
        <form id="menuForm">
            <input type="hidden" id="menuId">
            <div class="form-group"><label for="menuName">菜单名称</label><input type="text" class="form-control" id="menuName" required></div>
            <div class="form-group"><label for="menuUrl">菜单链接</label><input type="text" class="form-control" id="menuUrl"></div>
            <div class="form-group"><label for="parentId">父级菜单ID</label><input type="number" class="form-control" id="parentId"></div>
            <div class="form-group"><label for="sortOrder">排序</label><input type="number" class="form-control" id="sortOrder"></div>
            <div class="form-group"><label for="remark">备注</label><textarea class="form-control" id="remark" rows="3"></textarea></div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> 保存</button>
                <button type="button" class="btn btn-secondary" onclick="hideModal()"><i class="fas fa-times"></i> 取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 分配菜单模态框 -->
<div class="modal" id="assignModal">
    <div class="modal-content">
        <div class="modal-header"><h3>选择要分配菜单的用户</h3></div>
        <div class="user-list" id="userList">加载中...</div>
        <div class="modal-footer">
            <button class="btn btn-success" onclick="confirmAssign()">确认分配</button>
            <button class="btn btn-secondary" onclick="$('#assignModal').hide()">取消</button>
        </div>
    </div>
</div>

<script>
    let selectedMenuIds = [];
    let menusData = [];
    let isEditing = false;

    function showModal() { $('#menuModal').show(); }
    function hideModal() { $('#menuModal').hide(); isEditing = false; $("#editBtn").html('<i class="fas fa-edit"></i> 编辑'); }

    function loadMenus() {
        $.get("/sysMenu", function(data) {
            menusData = data;
            const tbody = $("#menuTableBody").empty();
            data.forEach(menu => {
                tbody.append(`
                    <tr onclick="toggleSelectMenu(${menu.menuId}, this)">
                        <td><input type="checkbox" value="${menu.menuId}" onclick="event.stopPropagation(); toggleSelectMenu(${menu.menuId}, this.closest('tr'))"></td>
                        <td>${menu.menuId}</td>
                        <td>${menu.menuName}</td>
                        <td>${menu.menuUrl || '-'}</td>
                        <td>${menu.parentId || '-'}</td>
                        <td>${menu.sortOrder}</td>
                        <td>${menu.remark || '-'}</td>
                    </tr>
                `);
            });
        });
    }

    function toggleSelectMenu(menuId, row) {
        if ($(row).hasClass('selected')) {
            $(row).removeClass('selected');
            selectedMenuIds = selectedMenuIds.filter(id => id !== menuId);
        } else {
            $(row).addClass('selected');
            selectedMenuIds.push(menuId);
        }
        $('input[type=checkbox]').each(function () {
            const id = parseInt($(this).val());
            $(this).prop("checked", selectedMenuIds.includes(id));
        });
        $('#editBtn').prop('disabled', selectedMenuIds.length !== 1);
        $('#deleteBtn, #assignBtn').prop('disabled', selectedMenuIds.length === 0);
    }

    function showAddModal() {
        $("#menuForm")[0].reset();
        $("#menuId").val('');
        $("#modalTitle").text('新增菜单');
        showModal();
    }

    function editSelectedMenu() {
        if (!isEditing) {
            if (selectedMenuIds.length !== 1) return alert('请选择一个菜单进行编辑');
            const menu = menusData.find(m => m.menuId == selectedMenuIds[0]);
            if (menu) {
                $("#menuId").val(menu.menuId);
                $("#menuName").val(menu.menuName);
                $("#menuUrl").val(menu.menuUrl);
                $("#parentId").val(menu.parentId);
                $("#sortOrder").val(menu.sortOrder);
                $("#remark").val(menu.remark);
                $("#modalTitle").text('编辑菜单');
                $("#editBtn").html('<i class="fas fa-save"></i> 保存');
                showModal();
                isEditing = true;
            }
        } else {
            $("#menuForm").submit();
            isEditing = false;
            $("#editBtn").html('<i class="fas fa-edit"></i> 编辑');
        }
    }

    function deleteSelectedMenu() {
        if (selectedMenuIds.length === 0) return alert('请选择要删除的菜单');
        if (!confirm("确定删除所选菜单？")) return;

        const deletePromises = selectedMenuIds.map(id =>
            $.ajax({ url: `/sysMenu/${id}`, method: "DELETE" })
        );

        Promise.all(deletePromises)
            .then(() => {
                loadMenus();
                selectedMenuIds = [];
                $('#editBtn, #deleteBtn, #assignBtn').prop('disabled', true);
                alert('✓ 删除成功');
            })
            .catch(() => alert('✗ 删除失败'));
    }

    function openAssignModal() {
        $.get("/sysUser", function(users) {
            const list = $("#userList").empty();
            users.forEach(user => {
                list.append(`<label><input type="checkbox" class="user-checkbox" value="${user.userId}"> ${user.userName}</label><br>`);
            });
            $("#assignModal").show();
        }).fail(() => {
            $("#userList").html("✗ 获取用户失败");
        });
    }

    function confirmAssign() {
        const userIds = $(".user-checkbox:checked").map(function() {
            return $(this).val();
        }).get();

        if (userIds.length === 0) return alert("请选择要分配的用户");

        $.ajax({
            url: "/roleMenu/assign",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify({ menuIds: selectedMenuIds, userIds: userIds }),
            success: function () {
                $("#assignModal").hide();
                selectedMenuIds = [];
                loadMenus();
                alert("✓ 分配成功");
                $('#editBtn, #deleteBtn, #assignBtn').prop('disabled', true);
            },
            error: function () {
                alert("✗ 分配失败");
            }
        });
    }

    $("#menuForm").submit(function (e) {
        e.preventDefault();

        const menuData = {
            menuId: $("#menuId").val(),
            menuName: $("#menuName").val(),
            menuUrl: $("#menuUrl").val(),
            parentId: $("#parentId").val(),
            sortOrder: $("#sortOrder").val(),
            remark: $("#remark").val()
        };

        const method = menuData.menuId ? "PUT" : "POST";
        const url = menuData.menuId ? `/sysMenu/${menuData.menuId}` : "/sysMenu";

        $.ajax({
            url: url,
            method: method,
            contentType: "application/json",
            data: JSON.stringify(menuData),
            success: function () {
                hideModal();
                loadMenus();
                selectedMenuIds = [];
                $('#editBtn, #deleteBtn, #assignBtn').prop('disabled', true);
                alert("✓ 保存成功");
            },
            error: function () {
                alert("✗ 保存失败");
            }
        });
    });

    $(document).ready(function () {
        loadMenus();
    });
</script>
</body>
</html>
